package com.wechatFriendExportTool.services.impl;

import com.wechatFriendExportTool.annotation.Service;
import com.wechatFriendExportTool.pojo.BoundPojo;
import com.wechatFriendExportTool.services.ComponentService;
import com.wechatFriendExportTool.utils.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;


/**
 * @author JiXin
 * @date 2023/9/19 下午4:20
 */
@Service
public class ComponentServiceImpl implements ComponentService {

    private final HashMap<String, Thread> threadHashMap = new HashMap<>();

    /**
     * 设置布局
     *
     * @Author: JiXin
     * @Date: 2023/9/19 下午4:21
     **/
    @Override
    public void setComponent(JPanel panel) throws AWTException {
        List<List<String>> excelList = new ArrayList<>();
        java.awt.Robot robot = new java.awt.Robot();
        JButton startExportJButton = SwingUtil.getJButton("开始导出", new Font(null, 1, 15), new BoundPojo(5, 5, 100, 20), new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                Thread startExportJButtonThread = threadHashMap.get("startExportJButton");

                if (startExportJButtonThread == null) {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (true) {
                                String clipboardText = "";
                                int errorWhile = 0;
                                while ("".equals(clipboardText) || clipboardText == null) {
                                    //获取微信的窗口并且置顶
                                    if (!EnhancedWeChatSwitcher.enhancedSwitchToWeChat()){
                                        //保存内容到Excel
                                        saveExcel(excelList,"获取微信程序失败");
                                        threadHashMap.remove("startExportJButton");
                                        return;
                                    }
                                    //开始copy好友信息
                                    copy(robot);

                                    //获取剪贴板内容
                                    clipboardText = ClipboardReader.getClipboardText();
                                    if ("".equals(clipboardText) || clipboardText == null) {
                                        System.out.println("剪贴板内容为空,正常重试复制");
                                    } else {
                                        System.out.println("获取剪贴板内容 ==> " + clipboardText.replaceAll("\n","  "));
                                    }

                                    //设置重试次数,防止一直重试导致数据一直无法保存,最后丢失数据
                                    if (errorWhile++ > 5){
                                        //保存内容到Excel
                                        saveExcel(excelList,"无法获取新的数据");
                                        threadHashMap.remove("startExportJButton");
                                        return;
                                    }
                                }
                                //获取好友信息
                                List<String> text = getText(clipboardText);
                                //存储到本地
                                if (excelList.contains(text)) {
                                    break;
                                }
                                excelList.add(text);
                                //清空剪贴板内容
                                ClipboardReader.delClipboardText();

                                //获取微信的窗口并且置顶
                                if (!EnhancedWeChatSwitcher.enhancedSwitchToWeChat()){
                                    //保存内容到Excel
                                    saveExcel(excelList,"获取微信程序失败");
                                    threadHashMap.remove("startExportJButton");
                                    return;
                                }
                                //下一个好友
                                next(robot);
                            }
                            //保存内容到Excel
                            saveExcel(excelList,"好友列表已导出到桌面");
                            threadHashMap.remove("startExportJButton");
                        }
                    });
                    threadHashMap.put("startExportJButton", thread);
                    thread.start();
                }

            }
        });

        panel.add(startExportJButton);

        JButton endJButton = SwingUtil.getJButton("暂停", new Font(null, 1, 15), new BoundPojo(110, 5, 70, 20), new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //保存内容到Excel
                saveExcel(excelList,"好友列表已导出到桌面");
                Thread startExportJButtonThread = threadHashMap.get("startExportJButton");
                if (startExportJButtonThread == null){
                    return;
                }
                startExportJButtonThread.stop();
                threadHashMap.remove("startExportJButton");
            }
        });

        panel.add(endJButton);

        JButton clearCacheJButton = SwingUtil.getJButton("清空缓存", new Font(null, 1, 15), new BoundPojo(185, 5, 100, 20), new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                excelList.clear();
                showMessageDialog("缓存已清空!");
            }
        });

        panel.add(clearCacheJButton);
    }

    /**
     * 保存内容到Excel
     *
     * @param excelList
     */
    private static void saveExcel(List<List<String>> excelList,String msg) {
        //保存到文件
        SXSSFWorkbook wb = new SXSSFWorkbook(excelList.size() + 10);
        List<String> headList = new ArrayList<>();
        headList.add("备注");
        headList.add("昵称");
        headList.add("微信号");
        headList.add("地区");
        headList.add("标签");
        headList.add("标签");
        headList.add("标签");
        headList.add("元数据");
        ExcelUtil.addSheet(wb, "好友", headList, excelList);


        ExcelDesktopUtils.saveReportWithTimestamp(wb, "微信好友");

        showMessageDialog(msg);
    }

    private static void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(null, message, "提示", JOptionPane.INFORMATION_MESSAGE);
    }


    private void copy(java.awt.Robot robot) {
        try {

            //按下
            robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
            robot.keyPress(java.awt.event.KeyEvent.VK_A);
            robot.delay(500);
            //松开
            robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
            robot.keyRelease(java.awt.event.KeyEvent.VK_A);
            robot.delay(1000);

            //按下
            robot.keyPress(java.awt.event.KeyEvent.VK_CONTROL);
            robot.keyPress(java.awt.event.KeyEvent.VK_C);
            robot.delay(500);
            //松开
            robot.keyRelease(java.awt.event.KeyEvent.VK_CONTROL);
            robot.keyRelease(java.awt.event.KeyEvent.VK_C);
            robot.delay(1000);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void next(java.awt.Robot robot) {
        try {

            //按下
            robot.keyPress(java.awt.event.KeyEvent.VK_DOWN);
            robot.delay(100);
            //松开
            robot.keyRelease(java.awt.event.KeyEvent.VK_DOWN);
            robot.delay(1000);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<String> getText(String clipboardText) {
        //判断是否有备注
        boolean isRemarks = false;

        String[] split = clipboardText.split("\n");
        List<String> testList = Arrays.stream(split).collect(Collectors.toList());
        String element = clipboardText.replaceAll("\n", "   ");
        String name = testList.get(0);
        for (int i = testList.size() - 1; i > 0; i--) {
            String s = testList.get(i);
            if (s.equals(name)) {
                testList.remove(i);
                isRemarks = true;
                break;
            }
        }

        if (!isRemarks) {
            testList.add(0, "-");
        }
        int i = 8 - testList.size();
        for (int i1 = 0; i1 < i; i1++) {
            testList.add("-");
        }

        testList.set(7, element);
        return testList;
    }

    public static void main(String[] args) {
        String clipboardText = ClipboardReader.getClipboardText();
        List<String> text = new ComponentServiceImpl().getText(clipboardText);
        for (String s : text) {
            System.out.println(s);
        }
    }
}
